var express = require('express');
var router = express.Router();

const axios = require('axios');
const querystring = require('querystring');
const crypto = require('crypto');
const { Base64 } = require('js-base64');
const app = express();
// 快递鸟 API 配置
const EBusinessID = '1874372';  // 替换为你的 EBusinessID
const AppKey = 'd5659c30-a2c2-4883-876f-cf02339e166b';  // 替换为你的 AppKey


// 快递鸟的接口 URL
const API_URL = 'https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';

// 生成签名的方法（根据快递鸟文档）
const generateDataSign = (requestData) => {
    const md5 = crypto.createHash('md5');
    md5.update(requestData + AppKey);
    return Base64.encode(md5.digest('hex'));
};

// 解析请求数据并准备发送
const getRequestData = (logisticsCode, trackingNumber) => {
    const requestData = JSON.stringify({
        ShipperCode: logisticsCode,  // 快递公司编码
        LogisticCode: trackingNumber, // 运单号
        RequestType: 8003,
    });

    const data = {
        RequestData: requestData,
        EBusinessID: EBusinessID,
        AppKey: AppKey,
        RequestType: 8003,  // 请求类型，8002 为物流跟踪
        DataSign: generateDataSign(requestData),
        DataType: '2'  // 返回格式，2 为 JSON 格式
    };

    return data;
};

// 查询物流轨迹的路由
router.get('/track', async (req, res) => {
    //   const { logisticsCode, trackingNumber } = req.query;
    const logisticsCode = req.query.logisticsCode
    const trackingNumber = req.query.trackingNumber
    console.log(logisticsCode, trackingNumber)

    // 准备请求数据
    const requestData = getRequestData(logisticsCode, trackingNumber);

    // 将请求数据转为 application/x-www-form-urlencoded 格式
    const postData = querystring.stringify(requestData);

    try {
        // 发起请求，设置表单数据编码格式
        const response = await axios.post(API_URL, postData, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
            }
        });

        // 处理响应
        if (response.data && response.data.Status === 200) {
            res.json(response.data);  // 返回查询结果
        } else {
            res.status(200).json({ error: '查询', details: response.data });
        }
    } catch (error) {
        res.status(500).json({ error: '请求失败', details: error.message });
    }
});

const request = require('request')

var { UserModel, ListModel } = require('../model/model')
//人脸登录验证识别接口
router.post("/face", async (req, res) => {
    const AK = "DG59594sEPgblOCdiJpiEWZH"
    const SK = "Jk0pmbByejKjITb2TQ6MH2gYdxIbEIdh"

    const { imageData } = req.body;

    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=' + await getAccessToken(),
        'headers': {
            'Content-Type': 'application/json'
        },
        // image 可以通过 getFileContentAsBase64("C:\fakepath\download.png") 方法获取,
        data: JSON.stringify({
            "group_id_list": "xmface",
            "image": imageData,
            "image_type": "BASE64"
        })

    };
    axios(options)
        .then(response => {
            console.log(response.data, '222222222222222222222222222222222');
            console.log(response.data.result.user_list[0]);
            console.log(response.data.result);
            if (response.data.error_code === 0) {
                if (response.data.result.user_list[0].score >= 80) {
                    res.send({
                        code: 200,
                        msg: "人脸识别成功",
                        name_id: response.data.result.user_list[0].user_id

                    })
                } else {
                    res.send({ code: 401, message: '人脸识别失败' })
                }
            } else {
                res.send({ code: 401, message: '人脸识别失败' })
            }
        }).catch(error => {
            res.send({ code: 401, msg: '检测不到人脸' })
        })
    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */

    function getAccessToken() {

        let options = {
            'method': 'POST',
            'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
        }
        return new Promise((resolve, reject) => {
            axios(options)
                .then(res => {
                    resolve(res.data.access_token)
                })
                .catch(error => {
                    reject(error)
                })
        })
    }
})


router.post("/list", async (req, res) => {
    console.log(req.body);
    res.send(req.body)
})









// 启动 Express 服务
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});














var { UserModel, ListModel } = require('../model/model')
//人脸登录验证识别接口
router.post("/face", async (req, res) => {
    const AK = "DG59594sEPgblOCdiJpiEWZH"
    const SK = "Jk0pmbByejKjITb2TQ6MH2gYdxIbEIdh"

    const { imageData } = req.body;

    var options = {
        'method': 'POST',
        'url': 'https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=' + await getAccessToken(),
        'headers': {
            'Content-Type': 'application/json'
        },
        // image 可以通过 getFileContentAsBase64("C:\fakepath\download.png") 方法获取,
        data: JSON.stringify({
            "group_id_list": "xmface",
            "image": imageData,
            "image_type": "BASE64"
        })

    };
    axios(options)
        .then(response => {
            console.log(response.data, '222222222222222222222222222222222');
            console.log(response.data.result.user_list[0]);
            console.log(response.data.result);
            if (response.data.error_code === 0) {
                if (response.data.result.user_list[0].score >= 80) {
                    res.send({
                        code: 200,
                        msg: "人脸识别成功",
                        name_id: response.data.result.user_list[0].user_id

                    })
                } else {
                    res.send({ code: 401, message: '人脸识别失败' })
                }
            } else {
                res.send({ code: 401, message: '人脸识别失败' })
            }
        }).catch(error => {
            res.send({ code: 401, msg: '检测不到人脸' })
        })
    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */

    function getAccessToken() {

        let options = {
            'method': 'POST',
            'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
        }
        return new Promise((resolve, reject) => {
            axios(options)
                .then(res => {
                    resolve(res.data.access_token)
                })
                .catch(error => {
                    reject(error)
                })
        })
    }
})


router.post("/list", async (req, res) => {
    console.log(req.body);
    res.send(req.body)
})
module.exports = router;
